<?php

namespace App\Admin\Controllers;

use App\AdminPermission;
use App\AdminRole;

class RoleController extends Controller
{
    //角色列表页面
    public function index()
    {
        $roles = AdminRole::all();
        
        return view('/admin/role/index', compact('roles'));
    }

    //角色添加页面
    public function create()
    {
        return view('/admin/role/add');
    }

    //角色添加行为
    public function store()
    {
        $this->validate(request(), [
            'name'       => 'required|min:3',
            'description'=>'required'
        ]);

        $name = request('name');
        $description = request('description');

        AdminRole::create(compact('name', 'description'));

        return redirect('/admin/roles');
    }

    //用户拥有的角色列表 AdminRole $role
    public function permission(AdminRole $role)
    {
        $permissions = AdminPermission::all();
        $rolePermissions = $role->permissions;

        return view('admin/role/permission', compact('permissions', 'rolePermissions', 'role'));
    }

    //保存角色的权限设置
    public function storePermission(AdminRole $role)
    {
        $this->validate(request(), [
            'permissions' => 'required|array'
        ]);

        $permissions = AdminPermission::findMany(request('permissions'));
        $myPermission = $role->permissions;

        //要添加的权限
        $addPermissions = $permissions->diff($myPermission);
        foreach ($addPermissions as $perm) {
            $role->grantPermission($perm);
        }

        //要删除的权限
        $delPermissions = $myPermission->diff($permissions);
        foreach ($delPermissions as $perm) {
            $role->deletePermission($perm);
        }

        return back();
    }
}
